package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R addCaiPin(@RequestBody Category category){
        log.info("category:{}",category);

        boolean save = categoryService.save(category);
        return save ? R.success("新增分类成功") : R.error("新增分类失败");

    }

    @GetMapping("/page")
    public R All(Integer page, Integer pageSize){

        IPage<Category> pageIfo = new Page<>(page,pageSize);
        categoryService.page(pageIfo);
        long total = pageIfo.getTotal();
        List<Category> records = pageIfo.getRecords();
        Map map = new HashMap();
        map.put("records",records);
        map.put("total",total);
        return R.success(map);
    }

    @DeleteMapping
    public R delete(Long id){
        log.info("删除分类，id为：{}",id);
        R r = categoryService.deleteById(id);
        return r;
    }

    @PutMapping
    public R update(@RequestBody Category category, HttpServletRequest request){

        Long employeeId = (Long) request.getSession().getAttribute("employee");
        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(employeeId);
        boolean update = categoryService.updateById(category);
        return update ? R.success("修改分类成功") : R.error("修改分类失败");
    }
/**
 * 根据条件查询分类数据
 * @param category
 * @return
 */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType() != null,Category::getType,category.getType());
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }

}
